using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.ReportForms;
using SupplierCustomerManagement.Read.API.Applications.Commands.reportforms;
using SupplierCustomerManagement.Read.API.Dtos;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.reportforms
{
    /// <summary>
    /// 获取存栏统计汇总列表 查询处理器
    /// </summary>
    public class GetSheepInventorySummariesQueryHandler : IRequestHandler<GetSheepInventorySummariesQuery, ApiPaging<SheepInventorySummaryListDto>>
    {
        private readonly IBaseRepository<SheepInventorySummary> _summaryRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetSheepInventorySummariesQueryHandler> _logger;

        public GetSheepInventorySummariesQueryHandler(
            IBaseRepository<SheepInventorySummary> summaryRepository,
            IMapper mapper,
            ILogger<GetSheepInventorySummariesQueryHandler> logger)
        {
            _summaryRepository = summaryRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiPaging<SheepInventorySummaryListDto>> Handle(GetSheepInventorySummariesQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询存栏统计列表，页码: {PageIndex}, 大小: {PageSize}", request.PageIndex, request.PageSize);

                var query = _summaryRepository.GetAll().Where(x => !x.IsDeleted);

               
                if (!string.IsNullOrWhiteSpace(request.SheepType))
                {
                    query = query.Where(x => x.SheepType == request.SheepType);
                }
                if (!string.IsNullOrWhiteSpace(request.Breed))
                {
                    query = query.Where(x => x.Breed != null && x.Breed.Contains(request.Breed));
                }
               
                if (request.StartDate.HasValue)
                {
                    query = query.Where(x => x.ReportDate >= request.StartDate.Value.Date);
                }
                if (request.EndDate.HasValue)
                {
                    var inclusiveEnd = request.EndDate.Value.Date.AddDays(1).AddTicks(-1);
                    query = query.Where(x => x.ReportDate <= inclusiveEnd);
                }

                var totalCount = await query.CountAsync(cancellationToken);
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);

                var entities = await query
                    .OrderByDescending(x => x.ReportDate)
                    .ThenBy(x => x.SheepType)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                var dtos = _mapper.Map<List<SheepInventorySummaryListDto>>(entities);

                return new ApiPaging<SheepInventorySummaryListDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    PageData = dtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询存栏统计列表发生异常");
                return new ApiPaging<SheepInventorySummaryListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询存栏统计列表失败: {ex.Message}",
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<SheepInventorySummaryListDto>()
                };
            }
        }
    }
}

